package com.farah.lease.web.app.controller.user;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.farah.lease.common.constant.RedisConstant;
import com.farah.lease.common.exception.LeaseException;
import com.farah.lease.common.login.LoginUserHolder;
import com.farah.lease.common.result.Result;
import com.farah.lease.common.result.ResultCodeEnum;
import com.farah.lease.model.entity.UserInfo;
import com.farah.lease.web.app.service.UserInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 不爱跑步的法拉韶
 * @Date 2024-07-08__15:00
 * @Description 用户信息管理
 **/

@Tag(name = "用户信息管理")
@RestController
@RequestMapping("/app/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("checkCode")
    @Operation(summary = "验证码校验")
    public Result checkCode(@RequestParam(name = "phone") String phone, @RequestParam(name = "code") String code) {
            String key = RedisConstant.APP_LOGIN_PREFIX +phone;
            String RCode = stringRedisTemplate.opsForValue().get(key);
            if (RCode==null) {
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
            }
            if (!RCode.equals(code)) {
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
            }
        return Result.ok();
    }
    @Operation(summary = "更新用户信息")
    @PostMapping("update")
    public Result updateUserInfoById(@RequestBody UserInfo userInfo){

        Long id= LoginUserHolder.getLoginUser().getUserId();
        LambdaUpdateWrapper<UserInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserInfo::getId, id);
        if(userInfo.getNickname() != null){
            wrapper.set(UserInfo::getNickname, userInfo.getNickname());
        }
        if(userInfo.getPassword()!=null){
            wrapper.set(UserInfo::getPassword, userInfo.getPassword());
        }
        if(userInfo.getAvatarUrl()!=null){
            wrapper.set(UserInfo::getAvatarUrl, userInfo.getAvatarUrl());
        }
        userInfoService.update(userInfo, wrapper);
        return Result.ok();
    }



}
